<?php
class eb2Controller
{
     protected $strModule;
     protected $strAction;
	 
     protected $oCurrentModule;
     protected $strCurrentAction;	
	 
	 protected $oModel;
	 private   $oRequest; //eb2Request 
	 private   $oUser; //eb2User    
	 
	 public function __construct(eb2Request $oRequest, eb2User $oUser)
	 { 
		$this->oRequest = $oRequest;
		$this->oUser    = $oUser;
	 }
	 
	 public static function main(eb2Request $oRequest, eb2User $oUser)
	 {
		$oController = new eb2Controller( $oRequest, $oUser );
		$oController->dispatch();
	 }
	 
	 public function dispatch()
	 {
	 	$strModule = $this->oRequest->getParameter('m');
	 	$strAction = $this->oRequest->getParameter('a');
		$this->oModel  = new eb2Model();
	 	list($this->strModule, $this->strAction) = $this->setModuleAction($strModule, $strAction);
		$this->execute();
	 }
	 
	 public function execute()
	 {
	    $aViewVars=array();
	 	if($this->checkPerms($this->strModule, $this->strAction, $this->oUser))
		{
			$this->oCurrentModule = $this->getObjModule($this->strModule);
			$this->strCurrentAction = $this->strAction;
		}else
		{
			$this->oCurrentModule = $this->getObjModule(SECURITY_MODULE);
			$this->strCurrentAction = SECURITY_ACTION_PERM;
		}
		try
		{
			 if($this->oCurrentModule->{$this->strAction}($aViewVars))
			 {
				$oView = new eb2View($aViewVars);
				try{
					$oView->render($this->oCurrentModule, $this->strCurrentAction);
				}catch(Exception $e)
				{
					trigger_error("The Current View could not be renderized");		
				}
			 }
		}catch(Exception $e)
		{
			trigger_error("The request Module could not be instanced");
		}
	 }
	 
	 private function getObjModule($srtModule)
	 {
	    if (include_once CONTROLLER_DIR . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . $srtModule . '.class.php') {
           return new $srtModule;
       } else {
			   throw new Exception ('Module not found');
       }
	 }
	 
	 private function setModuleAction($strModule, $strAction)
	 {
	 	if(!trim($strModule))
			$strModule = 'eb2Default';
	 	if(!trim($strAction))
			$strAction = 'index';
	 	return array($strModule, $strAction);
	 }
	 
	 private function checkPerms($strModule, $strAction, eb2User $oUser)
	 {
	 	return true;
	 }
}
?>